import 'package:flutter/material.dart';
import 'dart:math';
import 'dart:async';
import '../theme/app_theme.dart';
import '../services/period_service.dart';
import '../services/app_state_provider.dart';
import '../models/period_model.dart';
import 'today_report_screen.dart';



class MoonCompanionScreen extends StatefulWidget {
  const MoonCompanionScreen({super.key});

  @override
  MoonCompanionScreenState createState() => MoonCompanionScreenState();
}

class MoonCompanionScreenState extends State<MoonCompanionScreen> {
  final PeriodService _periodService = PeriodService();
  CycleInfo? cycleInfo;
  bool isPeriodActive = false; 

  bool isDatePickerVisible = false; 

  Timer? _refreshTimer; 

  bool _isLoading = true; 

  bool _isInitialized = false; 


  @override
  void initState() {
    super.initState();

    
    _refreshTimer = Timer.periodic(const Duration(seconds: 30), (timer) {
      if (mounted) {
        _refreshData();
      }
    });
  }

  
  void _showPeriodEndDatePicker() {
    setState(() {
      isDatePickerVisible = true;
    });

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          height: MediaQuery.of(context).size.height * 0.4,
          decoration: const BoxDecoration(
            color: AppTheme.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
          ),
          child: Column(
            children: [
              
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                decoration: const BoxDecoration(
                  border: Border(bottom: BorderSide(color: Color(0xFFF0F0F0))),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    InkWell(
                      onTap: () {
                        Navigator.pop(context);
                        setState(() {
                          isDatePickerVisible = false;
                        });
                      },
                      borderRadius: BorderRadius.circular(8),
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 16, vertical: 12),
                        child: const Text(
                          '取消',
                          style: TextStyle(color: Color(0xFF999999)),
                        ),
                      ),
                    ),
                    Text(
                      '月经什么时候走的？',
                      style: AppTheme.bodyStyle
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                    InkWell(
                      onTap: () {
                        Navigator.pop(context, DateTime.now());
                      },
                      borderRadius: BorderRadius.circular(8),
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 16, vertical: 12),
                        child: const Text(
                          '确定',
                          style: TextStyle(color: AppTheme.primaryColor),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              
              Container(
                padding: const EdgeInsets.all(16),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    
                    InkWell(
                      onTap: () {
                        debugPrint('前天按钮被点击');
                        try {
                          final selectedDate =
                              DateTime.now().subtract(const Duration(days: 2));
                          Navigator.pop(context, selectedDate);
                          debugPrint('前天日期已传递: $selectedDate');
                        } catch (e) {
                          debugPrint('前天按钮点击错误: $e');
                        }
                      },
                      borderRadius: BorderRadius.circular(8),
                      child: Container(
                        width: double.infinity,
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(color: const Color(0xFFF0F0F0)),
                        ),
                        child: Text(
                          '${DateTime.now().subtract(const Duration(days: 2)).day}日(前天)',
                          style: AppTheme.bodyStyle,
                        ),
                      ),
                    ),
                    const SizedBox(height: 12),
                    
                    InkWell(
                      onTap: () {
                        debugPrint('昨天按钮被点击');
                        try {
                          final selectedDate =
                              DateTime.now().subtract(const Duration(days: 1));
                          Navigator.pop(context, selectedDate);
                          debugPrint('昨天日期已传递: $selectedDate');
                        } catch (e) {
                          debugPrint('昨天按钮点击错误: $e');
                        }
                      },
                      borderRadius: BorderRadius.circular(8),
                      child: Container(
                        width: double.infinity,
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(color: const Color(0xFFF0F0F0)),
                        ),
                        child: Text(
                          '${DateTime.now().subtract(const Duration(days: 1)).day}日(昨天)',
                          style: AppTheme.bodyStyle,
                        ),
                      ),
                    ),
                    const SizedBox(height: 12),
                    
                    InkWell(
                      onTap: () {
                        debugPrint('今天按钮被点击');
                        try {
                          final selectedDate = DateTime.now();
                          Navigator.pop(context, selectedDate);
                          debugPrint('今天日期已传递: $selectedDate');
                        } catch (e) {
                          debugPrint('今天按钮点击错误: $e');
                        }
                      },
                      borderRadius: BorderRadius.circular(8),
                      child: Container(
                        width: double.infinity,
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        alignment: Alignment.center,
                        decoration: const BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(8)),
                          border: Border.fromBorderSide(
                              BorderSide(color: AppTheme.primaryColor)),
                          color: Color(0xFFFCE4EC),
                        ),
                        child: Text(
                          '${DateTime.now().year}年 ${DateTime.now().month}月 ${DateTime.now().day}日(今天)',
                          style: AppTheme.bodyStyle
                              .copyWith(color: AppTheme.primaryColor),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    ).then((selectedDate) async {
      debugPrint('月经结束日期选择器返回: $selectedDate');
      
      setState(() {
        isDatePickerVisible = false;
      });

      if (selectedDate != null) {
        debugPrint('选择了月经结束日期: $selectedDate');
        try {
          final appState = AppStateProvider.of(context);
          debugPrint('获取AppStateProvider成功');

          
          if (selectedDate.isAfter(DateTime.now())) {
            debugPrint('错误：选择了未来日期');
            _showError('不能记录未来的日期');
            return;
          }

          if (selectedDate
              .isBefore(DateTime.now().subtract(const Duration(days: 365)))) {
            debugPrint('错误：选择了过早的日期');
            _showError('不能记录超过一年前的日期');
            return;
          }

          debugPrint('记录月经结束: $selectedDate');
          await appState.recordPeriodEnd(selectedDate);
          debugPrint('月经结束记录完成');

          
          await _refreshData();
          debugPrint('数据刷新完成');

          _showSuccess('月经结束日期已记录');
        } catch (e, stackTrace) {
          debugPrint('记录失败: $e');
          debugPrint('错误堆栈: $stackTrace');
          _showError('记录失败: ${e.toString()}');
        }
      } else {
        debugPrint('用户取消了日期选择');
      }
    });
  }

  @override
  void dispose() {
    _refreshTimer?.cancel();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    
    if (!_isInitialized) {
      _isInitialized = true;
      _initializeData();
    } else {
      
      _refreshData();
    }
  }

  
  Future<void> _initializeData() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final appState = AppStateProvider.of(context);

      

      
      final info = await _periodService.getCycleInfo();

      
      _validateCycleInfo(info);

      setState(() {
        cycleInfo = info;
        isPeriodActive = appState.isPeriodActive;
        _isLoading = false;
      });
    } catch (e) {
      debugPrint('初始化数据失败: $e');

      
      if (mounted) {
        Future.delayed(Duration.zero, () {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('数据加载失败: ${e.toString()}'),
                backgroundColor: Colors.red,
                duration: const Duration(seconds: 3),
              ),
            );
          }
        });
      }

      setState(() {
        _isLoading = false;
      });
    }
  }

  
  void _validateCycleInfo(CycleInfo info) {    
    final now = DateTime.now();
    final maxFutureDate = now.add(const Duration(days: 365)); 

    if (info.nextPeriodDate.isBefore(now.subtract(const Duration(days: 30)))) {
      debugPrint('警告: 预测的经期日期过于久远: ${info.nextPeriodDate}');
    }

    if (info.nextPeriodDate.isAfter(maxFutureDate)) {
      debugPrint('警告: 预测的经期日期过于遥远: ${info.nextPeriodDate}');
    }

    
    if (info.cycleLength < 21 || info.cycleLength > 45) {
      debugPrint('警告: 异常的周期长度: ${info.cycleLength}天');
    }

    
    if (info.periodLength < 3 || info.periodLength > 10) {
      debugPrint('警告: 异常的经期长度: ${info.periodLength}天');
    }

    
    if (info.pregnancyRate < 0 || info.pregnancyRate > 100) {
      debugPrint('警告: 异常的怀孕几率: ${info.pregnancyRate}%');
    }

    
    if (info.healthScore < 0 || info.healthScore > 100) {
      debugPrint('警告: 异常的健康评分: ${info.healthScore}');
    }
  }

  
  Future<void> _refreshData() async {
    try {
      final appState = AppStateProvider.of(context);

      
      

      
      final info = await _periodService.getCycleInfo();

      
      _validateCycleInfo(info);

      
      final bool currentlyInPeriod = appState.isPeriodActive;

      if (mounted) {
        setState(() {
          cycleInfo = info;
          isPeriodActive = currentlyInPeriod; 

        });
      }
    } catch (e) {
      debugPrint('刷新数据失败: $e');

      
      if (mounted) {
        Future.delayed(Duration.zero, () {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('数据刷新失败: ${e.toString()}'),
                backgroundColor: Colors.orange,
                duration: const Duration(seconds: 2),
              ),
            );
          }
        });
      }
    }
  }

  
  Color getYesButtonColor() {
    
    if (isPeriodActive) {
      return const Color(0xFFDDDDDD);
    }
    return isDatePickerVisible
        ? AppTheme.primaryColor
        : const Color(0xFFDDDDDD);
  }

  
  Color getNoButtonColor() {
    
    if (isPeriodActive) {
      return AppTheme.primaryColor;
    }
    return isDatePickerVisible
        ? const Color(0xFFDDDDDD)
        : AppTheme.primaryColor;
  }

  
  void _showError(String message) {
    if (mounted) {
      Future.delayed(Duration.zero, () {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(message),
              backgroundColor: Colors.red[400],
              duration: const Duration(seconds: 3),
            ),
          );
        }
      });
    }
  }

  
  void _showSuccess(String message) {
    if (mounted) {
      Future.delayed(Duration.zero, () {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(message),
              backgroundColor: Colors.green[400],
              duration: const Duration(seconds: 2),
            ),
          );
        }
      });
    }
  }

  
  void _showDatePicker() {
    
    if (isPeriodActive) {
      _showError('当前已处于经期，无需重复记录');
      return;
    }
    
    setState(() {
      isDatePickerVisible = true;
    });

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      barrierColor: Colors.black54,
      enableDrag: false,
      isDismissible: true,
      builder: (context) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(color: Color(0xFFF0F0F0)),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  InkWell(
                    onTap: () {
                      Navigator.pop(context);
                      setState(() {
                        isDatePickerVisible = false;
                      });
                    },
                    borderRadius: BorderRadius.circular(8),
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 12),
                      child: const Text(
                        '取消',
                        style: TextStyle(color: Color(0xFF999999)),
                      ),
                    ),
                  ),
                  Text(
                    isPeriodActive ? '什么时候走的？' : '选择经期开始日期',
                    style: AppTheme.bodyStyle
                        .copyWith(fontWeight: FontWeight.bold),
                  ),
                  InkWell(
                    onTap: () {
                      Navigator.pop(context, DateTime.now());
                    },
                    borderRadius: BorderRadius.circular(8),
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 12),
                      child: const Text(
                        '确定',
                        style: TextStyle(color: AppTheme.primaryColor),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            Container(
              padding: const EdgeInsets.all(16),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  
                  InkWell(
                    onTap: () {
                      debugPrint('前天按钮被点击');
                      try {
                        final selectedDate =
                            DateTime.now().subtract(const Duration(days: 2));
                        Navigator.pop(context, selectedDate);
                        debugPrint('前天日期已传递: $selectedDate');
                      } catch (e) {
                        debugPrint('前天按钮点击错误: $e');
                      }
                    },
                    borderRadius: BorderRadius.circular(8),
                    child: Container(
                      width: double.infinity,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: const Color(0xFFF0F0F0)),
                      ),
                      child: Text(
                        '${DateTime.now().subtract(const Duration(days: 2)).day}日(前天)',
                        style: AppTheme.bodyStyle,
                      ),
                    ),
                  ),
                  const SizedBox(height: 12),
                  
                  InkWell(
                    onTap: () {
                      debugPrint('昨天按钮被点击');
                      try {
                        final selectedDate =
                            DateTime.now().subtract(const Duration(days: 1));
                        Navigator.pop(context, selectedDate);
                        debugPrint('昨天日期已传递: $selectedDate');
                      } catch (e) {
                        debugPrint('昨天按钮点击错误: $e');
                      }
                    },
                    borderRadius: BorderRadius.circular(8),
                    child: Container(
                      width: double.infinity,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: const Color(0xFFF0F0F0)),
                      ),
                      child: Text(
                        '${DateTime.now().subtract(const Duration(days: 1)).day}日(昨天)',
                        style: AppTheme.bodyStyle,
                      ),
                    ),
                  ),
                  const SizedBox(height: 12),
                  
                  InkWell(
                    onTap: () {
                      debugPrint('今天按钮被点击');
                      try {
                        final selectedDate = DateTime.now();
                        Navigator.pop(context, selectedDate);
                        debugPrint('今天日期已传递: $selectedDate');
                      } catch (e) {
                        debugPrint('今天按钮点击错误: $e');
                      }
                    },
                    borderRadius: BorderRadius.circular(8),
                    child: Container(
                      width: double.infinity,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      alignment: Alignment.center,
                      decoration: const BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(8)),
                        border: Border.fromBorderSide(
                            BorderSide(color: AppTheme.primaryColor)),
                        color: Color(0xFFFCE4EC),
                      ),
                      child: Text(
                        '${DateTime.now().year}年 ${DateTime.now().month}月 ${DateTime.now().day}日(今天)',
                        style: AppTheme.bodyStyle
                            .copyWith(color: AppTheme.primaryColor),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    ).then((selectedDate) async {
      debugPrint('日期选择器返回: $selectedDate');
      
      setState(() {
        isDatePickerVisible = false;
      });

      if (selectedDate != null) {
        debugPrint('选择了日期: $selectedDate');
        try {
          final appState = AppStateProvider.of(context);
          debugPrint('获取AppStateProvider成功');

          
          if (selectedDate.isAfter(DateTime.now())) {
            debugPrint('错误：选择了未来日期');
            _showError('不能记录未来的日期');
            return;
          }

          if (selectedDate
              .isBefore(DateTime.now().subtract(const Duration(days: 365)))) {
            debugPrint('错误：选择了过早的日期');
            _showError('不能记录超过一年前的日期');
            return;
          }

          debugPrint('当前经期状态: isPeriodActive = $isPeriodActive');

          if (isPeriodActive) {
            
            debugPrint('记录月经结束: $selectedDate');
            await appState.recordPeriodEnd(selectedDate);
            debugPrint('月经结束记录完成');

            
            await _refreshData();
            debugPrint('数据刷新完成');

            _showSuccess('月经结束日期已记录');
          } else {
            
            debugPrint('记录月经开始: $selectedDate');
            await appState.recordPeriodStart(selectedDate);
            debugPrint('月经开始记录完成');

            
            await _refreshData();
            debugPrint('数据刷新完成');

            _showSuccess('月经开始日期已记录');
          }
        } catch (e, stackTrace) {
          debugPrint('记录失败: $e');
          debugPrint('错误堆栈: $stackTrace');
          _showError('记录失败: ${e.toString()}');
        }
      } else {
        debugPrint('用户取消了日期选择');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final appState = AppStateProvider.of(context);

    
    final cycleInfo = this.cycleInfo ?? appState.currentCycleInfo;

    
    int daysUntilNextPeriod = 28; 

    DateTime? nextPeriodDate;
    double pregnancyProbability = 0.0;

    if (cycleInfo != null) {
      
      daysUntilNextPeriod =
          cycleInfo.daysUntilNextPeriod.clamp(-30, 90); 

      nextPeriodDate = cycleInfo.nextPeriodDate;
      pregnancyProbability =
          cycleInfo.pregnancyRate.clamp(0.0, 100.0); 


      
      final now = DateTime.now();
      final maxFutureDate = now.add(const Duration(days: 365));

        if (nextPeriodDate.isBefore(now.subtract(const Duration(days: 30))) ||
            nextPeriodDate.isAfter(maxFutureDate)) {
          debugPrint('警告: 预测的经期日期不合理: $nextPeriodDate，使用默认值');
          
          daysUntilNextPeriod = (daysUntilNextPeriod < -90)
              ? -90
              : (daysUntilNextPeriod > 90 ? 90 : daysUntilNextPeriod);
          nextPeriodDate = now.add(Duration(days: daysUntilNextPeriod));
        }
    }

    
    String statusText = '';
    if (isPeriodActive) {
      
      if (daysUntilNextPeriod <= 0) {
        statusText = '经期最后一天';
      } else if (daysUntilNextPeriod > 30) {
        statusText = '经期异常，请联系客服'; 

      } else {
        statusText = '经期还有$daysUntilNextPeriod天';
      }
    } else {
      
      if (daysUntilNextPeriod < 0) {
        
        statusText = '经期已过期${daysUntilNextPeriod.abs()}天';
      } else if (daysUntilNextPeriod == 0) {
        statusText = '今天应该来月经';
      } else if (daysUntilNextPeriod > 90) {
        statusText = '数据异常，请重新设置'; 

      } else {
        statusText = '距月经开始还有$daysUntilNextPeriod天';
      }
    }

    return Scaffold(
      backgroundColor: AppTheme.background,
      appBar: AppBar(
        title: const Text(
          '月伴',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: AppTheme.textPrimary,
          ),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.white,
        elevation: 0,
        automaticallyImplyLeading: false,
      ),
      body: SafeArea(
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : Stack(
                children: [
                  SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          margin: const EdgeInsets.only(
                              top: 16, left: 16, right: 16),
                          padding: const EdgeInsets.all(16),
                          decoration: const BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(16)),
                            gradient: LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: [
                                Color.fromRGBO(255, 105, 180, 1.0),
                                Color.fromRGBO(255, 135, 195, 1.0),
                              ],
                            ),
                          ),
                          child: Stack(
                            children: [
                              Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      statusText,
                                      style: const TextStyle(
                                        fontSize: 20,
                                        fontWeight: FontWeight.bold,
                                        color: AppTheme.white,
                                      ),
                                    ),
                                    const SizedBox(height: 8),
                                    Row(
                                      children: [
                                        Text(
                                          '预测经期开始日${nextPeriodDate?.month ?? '--'}月${nextPeriodDate?.day ?? '--'}日',
                                          style: const TextStyle(
                                            fontSize: 14,
                                            color: Color.fromRGBO(
                                                255, 255, 255, 0.9),
                                          ),
                                        ),
                                        const SizedBox(width: 8),
                                        const Icon(
                                          Icons.chevron_right,
                                          size: 16,
                                          color: Color.fromRGBO(
                                              255, 255, 255, 0.9),
                                        ),
                                      ],
                                    ),
                                    const SizedBox(height: 12),
                                    ElevatedButton(
                                      onPressed: () {
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  const TodayReportScreen()),
                                        );
                                      },
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: AppTheme.white,
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 24, vertical: 8),
                                        shape: RoundedRectangleBorder(
                                          borderRadius:
                                              BorderRadius.circular(12),
                                        ),
                                      ),
                                      child: const Text(
                                        '查看详情',
                                        style: TextStyle(
                                          fontSize: 14,
                                          color: AppTheme.primaryColor,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ),
                                  ]),
                              Positioned(
                                top: 0,
                                right: 0,
                                child: ClipPath(
                                  clipper: FlowerShapeClipper(),
                                  child: Container(
                                    width: 100,
                                    height: 100,
                                    color:
                                        const Color.fromRGBO(255, 255, 255, 1)
                                            .withValues(alpha: 0.2),
                                    alignment: Alignment.center,
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Text(
                                          '怀孕几率',
                                          style: const TextStyle(
                                            fontSize: 12,
                                            color: AppTheme.white,
                                          ),
                                        ),
                                        Text(
                                          '${pregnancyProbability.toStringAsFixed(1)}%',
                                          style: const TextStyle(
                                            fontSize: 18,
                                            fontWeight: FontWeight.bold,
                                            color: AppTheme.white,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        
                        if (!isPeriodActive) ...[
                          Container(
                            margin: const EdgeInsets.only(
                                top: 20, left: 16, right: 16),
                            padding: const EdgeInsets.symmetric(
                                horizontal: 16, vertical: 8),
                            decoration: const BoxDecoration(
                              color: AppTheme.white,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(12)),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    const Icon(
                                      Icons.water_drop,
                                      size: 24,
                                      color: AppTheme.primaryColor,
                                    ),
                                    const SizedBox(width: 8),
                                    Text('月经来了', style: AppTheme.bodyStyle),
                                  ],
                                ),
                                Row(
                                  children: [
                                    
                                    GestureDetector(
                                      onTap: () {
                                        
                                        if (isPeriodActive) {
                                          _showError('当前已处于经期，无需重复记录');
                                          return;
                                        }
                                        _showDatePicker();
                                      },
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 16, vertical: 6),
                                        decoration: BoxDecoration(
                                          color: getYesButtonColor(),
                                          borderRadius: const BorderRadius.all(
                                              Radius.circular(4)),
                                        ),
                                        child: const Text(
                                          '是',
                                          style: TextStyle(
                                            fontSize: 14,
                                            color: Colors.white,
                                            fontWeight: FontWeight.normal,
                                          ),
                                        ),
                                      ),
                                    ),
                                    const SizedBox(width: 8),
                                    
                                    GestureDetector(
                                      onTap: () {
                                        
                                        if (mounted) {
                                          Future.delayed(Duration.zero, () {
                                            if (mounted) {
                                              ScaffoldMessenger.of(context)
                                                  .showSnackBar(
                                                const SnackBar(
                                                    content: Text(
                                                        '请点击"是"按钮选择月经开始日期')),
                                              );
                                            }
                                          });
                                        }
                                      },
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 16, vertical: 6),
                                        decoration: BoxDecoration(
                                          color: getNoButtonColor(),
                                          borderRadius: const BorderRadius.all(
                                              Radius.circular(4)),
                                        ),
                                        child: const Text(
                                          '否',
                                          style: TextStyle(
                                            fontSize: 14,
                                            color: Colors.white,
                                            fontWeight: FontWeight.normal,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ] else ...[
                          
                          Container(
                            margin: const EdgeInsets.only(
                                top: 20, left: 16, right: 16),
                            padding: const EdgeInsets.symmetric(
                                horizontal: 16, vertical: 8),
                            decoration: const BoxDecoration(
                              color: AppTheme.white,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(12)),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    const Icon(
                                      Icons.water_drop,
                                      size: 24,
                                      color: AppTheme.primaryColor,
                                    ),
                                    const SizedBox(width: 8),
                                    Text('月经走了？',
                                        style:
                                            AppTheme.bodyStyle), 

                                  ],
                                ),
                                Row(
                                  children: [
                                    
                                    GestureDetector(
                                      onTap: () {
                                        _showPeriodEndDatePicker();
                                      },
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 16, vertical: 6),
                                        decoration: BoxDecoration(
                                          color: AppTheme.primaryColor,
                                          borderRadius: const BorderRadius.all(
                                              Radius.circular(4)),
                                        ),
                                        child: const Text(
                                          '是',
                                          style: TextStyle(
                                            fontSize: 14,
                                            color: Colors.white,
                                            fontWeight: FontWeight.normal,
                                          ),
                                        ),
                                      ),
                                    ),
                                    const SizedBox(width: 8),
                                    
                                    GestureDetector(
                                      onTap: () {
                                        if (mounted) {
                                          Future.delayed(Duration.zero, () {
                                            if (mounted) {
                                              ScaffoldMessenger.of(context)
                                                  .showSnackBar(
                                                const SnackBar(
                                                    content:
                                                        Text('经期还未结束，继续记录吧')),
                                              );
                                            }
                                          });
                                        }
                                      },
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 16, vertical: 6),
                                        decoration: BoxDecoration(
                                          color: const Color(0xFFDDDDDD),
                                          borderRadius: const BorderRadius.all(
                                              Radius.circular(4)),
                                        ),
                                        child: const Text(
                                          '否',
                                          style: TextStyle(
                                            fontSize: 14,
                                            color: Colors.white,
                                            fontWeight: FontWeight.normal,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                          
                          Container(
                            margin: const EdgeInsets.only(
                                top: 8, left: 16, right: 16),
                            padding: const EdgeInsets.symmetric(
                                horizontal: 16, vertical: 12),
                            decoration: const BoxDecoration(
                              color: AppTheme.primaryColor,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(12)),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    const Icon(
                                      Icons.water_drop,
                                      size: 24,
                                      color: Colors.white,
                                    ),
                                    const SizedBox(width: 8),
                                    Text(
                                      '当前处于经期',
                                      style: AppTheme.bodyStyle
                                          .copyWith(color: Colors.white),
                                    ),
                                  ],
                                ),
                                
                                GestureDetector(
                                  onTap: () {
                                    
                                    if (mounted) {
                                      showDialog(
                                        context: context,
                                        builder: (context) => AlertDialog(
                                          title: const Text('确认'),
                                          content: const Text('确定要记录月经结束吗？'),
                                          actions: [
                                            TextButton(
                                              onPressed: () =>
                                                  Navigator.pop(context),
                                              child: const Text('取消'),
                                            ),
                                            TextButton(
                                              onPressed: () async {
                                                Navigator.pop(context);
                                                try {
                                                  final appState =
                                                      AppStateProvider.of(
                                                          context);
                                                  await appState
                                                      .recordPeriodEnd(
                                                          DateTime.now());
                                                  await _refreshData();
                                                  if (mounted) {
                                                    ScaffoldMessenger.of(
                                                            context)
                                                        .showSnackBar(
                                                      const SnackBar(
                                                          content: Text(
                                                              '月经结束日期已记录')),
                                                    );
                                                  }
                                                } catch (e) {
                                                  if (mounted) {
                                                    ScaffoldMessenger.of(
                                                            context)
                                                        .showSnackBar(
                                                      SnackBar(
                                                          content: Text(
                                                              '记录失败: ${e.toString()}')),
                                                    );
                                                  }
                                                }
                                              },
                                              child: const Text('确定'),
                                            ),
                                          ],
                                        ),
                                      );
                                    }
                                  },
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 12, vertical: 6),
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: const BorderRadius.all(
                                          Radius.circular(4)),
                                    ),
                                    child: Text(
                                      '记录结束',
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: AppTheme.primaryColor,
                                        fontWeight: FontWeight.normal,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                ],
              ),
      ),
    );
  }
}


class FlowerShapeClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path();
    final centerX = size.width / 2;
    final centerY = size.height / 2;
    final radius = min(size.width, size.height) / 2 - 2;

    path.addOval(
      Rect.fromCircle(
        center: Offset(centerX, centerY),
        radius: radius,
      ),
    );

    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }
}
